package org.example;

public class Base64 {
    public static char[] base64 = {
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K','L', 'M', 'N','O', 'P',
            'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f','g',
            'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v','w', 'x',
            'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
    };

    public static String ToBase64(byte[] bytes){
        String string="";
        int num = bytes.length % 3;
        int v;

        for (int i = 2; i < bytes.length; i += 3) {
            //每次取3位
            v = ((bytes[i - 2] & 0xff) << 16) | ((bytes[i - 1] & 0xff) << 8) | (bytes[i] & 0xff);

            //每次取6比特
            int d0 = v & 0x3f;
            int d1 = (v >>> 6) & 0x3f;
            int d2 = (v >>> 12) & 0x3f;
            int d3 = (v >>> 18) & 0x3f;

            string+=base64[d3];
            string+=base64[d2];
            string+=base64[d1];
            string+=base64[d0];
        }
        if (num > 1) {
            v = ((bytes[bytes.length - 2] & 0xff) << 16) | ((bytes[bytes.length - 1] & 0xff) << 8);

            int d1 = v >>> 6 & 0x3f;
            int d2 = v >>> 12 & 0x3f;
            int d3 = v >>> 18 & 0x3f;
            string+=base64[d3];
            string+=base64[d2];
            string+=base64[d1];
            string+="=";
        }
        if (num == 1) {
            v = ((bytes[bytes.length - 1] & 0xff) << 16);

            int d2 = v >>> 12 & 0x3f;
            int d3 = v >>> 18 & 0x3f;
            string+=base64[d3];
            string+=base64[d2];
            string+="=";
            string+="=";
        }
        return string;
    }
}
